package com.lxf.education.service.impl;


import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.lxf.education.dao.UserMapper;
import com.lxf.education.pojo.UserPojo;
import com.lxf.education.service.UserService;
import com.lxf.education.utils.RedisUtils;
import com.lxf.education.utils.ResultVo;
import com.sun.mail.util.MailSSLSocketFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;

import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;
/**
* @author:LuoXingFa;
* @version:Date:2022年4月18日下午4:05:49
*/
@Service
public class UserServiceImpl implements UserService{
	
	@Resource
    UserMapper userdao;
	
	@Autowired
	static HttpServletRequest request;
	
	@Autowired
	public static BCryptPasswordEncoder ecoder;
	
	@Autowired
	TemplateEngine template;
	
	//发件人
	@Value("${spring.mail.username}")
	private String username;
	
	//发送邮箱
	@Autowired
	JavaMailSender mailsender;

	// 过期时间
	@Value("${mail.code.overtime}")
    private Integer overtime; 
	
	@Resource
	RedisUtils redeisUtils;
	
	@Resource
	HttpServletRequest req;
	@Override
	public List<UserPojo> findUser(String username, String password) {
		 return userdao.getUser(username, password);
	    }

	/**
	 * 查询登录用户的所有信息
	 * @return
	 */
	@Override
	public  UserPojo findUserProfile(String username){

		return userdao.getUserByName(username);
	}

	/**
	 * 注册功能
	 */
	@Override
	public UserPojo insertUser(UserPojo user) {
		BCryptPasswordEncoder ecoder =new BCryptPasswordEncoder();
		user.setUname(req.getParameter("user"));
		user.setUpwd(ecoder.encode(req.getParameter("password")));//密码加密
		user.setUuname(req.getParameter("name"));
		user.setUemail(req.getParameter("email"));
		user.setUaccount(req.getParameter("account"));
		user.setUsex(req.getParameter("sex"));
		user.setUage(req.getParameter("age"));
		user.setUhoby(req.getParameter("lable"));
		int i = userdao.addUser(user);
		if (i==1) {
		    ResultVo.getSuccessVo("注册成功");
		    return user;
		}else {
			ResultVo.getFailVo("注册失败！");
			return null;
		}
		
	}

	/**
	 * @根据用户名查询密码
	 */
	@Override
	public String findPWDByName(String username) {
		// TODO Auto-generated method stub
		return userdao.getPwdByName(username);
	}
	/**
	 * @获取邮箱验证码
	 */
	@Override
	public ResultVo getCode(String mailAddress){
		// TODO Auto-generated method stub
		//注：此处的session不能使用@Autowired注入的request来获取，否则将会报null
		HttpSession session1 = req.getSession(false);
		//非空校验
		if (mailAddress==null||"".equals(mailAddress))return ResultVo.getFailVo("邮箱地址不能为空！");
		UserPojo user = userdao.getUserByEmail(mailAddress);
		if (!user.getUemail().equals(mailAddress)) {
			return ResultVo.getFailVo("该邮箱不存在或未绑定用户，请重新输入");
		}else {
		String vertifyCode = createVertifyCode();

		//开启属性配置
		Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密，否则会失败
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        // 创建session
        Session session = Session.getInstance(prop);

        try {
            Transport ts = session.getTransport();
            try {
                // 连接邮件服务器：邮箱类型，帐号，POP3/SMTP协议授权码 .163使用：smtp.163.com
                ts.connect("smtp.qq.com", "2491431173", "wvtbswyhywbeeccg");
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            Message message = null;
            try {
//                // 创建邮件
                message = createSimpleMail(session,vertifyCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                //修改邮件接收方为传入的参数(邮件地址)
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailAddress));
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            // 发送邮件
            try {
                ts.sendMessage(message, message.getAllRecipients());
        		//将验证码存入session中
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        		session1.setMaxInactiveInterval(60);
        		session1.setAttribute("vertifyCode",encoder.encode(vertifyCode));
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            try {
                ts.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
       
        //返回验证码给前端
        return ResultVo.getSuccessVo("success", vertifyCode);
		}
    }
	 //  获取6位随机验证码
    public String createVertifyCode(){
        String[] letters = new String[] {
                "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
                "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
                "0","1","2","3","4","5","6","7","8","9"};
        String stringBuilder ="";
        for (int i = 0; i < 6; i++) {
            stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)];
        }
        return stringBuilder;
        
    }
    public static MimeMessage createSimpleMail(Session session, String str) throws Exception {
    	// 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("2491431173@qq.com"));
        // 指明邮件的收件人，发件人和收件人如果是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("2491431173@qq.com"));
        // 邮件的标题
        message.setSubject("听风--教评系统--验证码");
        // 邮件的文本内容
        message.setContent("您正在使用听风--教评系统的密码修改服务,密码重置的验证码为:"+str+"(该验证码一分钟后将无效),若您无以上操作,请忽略此信息,请勿回复此邮箱", "text/html;charset=UTF-8");
        
        return message;
    }

	/**
	 * @通过邮箱查询该用户是否存在
	 */
	@Override
	public UserPojo findUserByEmail(String email) {
		// TODO Auto-generated method stub
		return userdao.getUserByEmail(email);
	}
	/**
	 * @根据验证码找回密码
	 */
	@Override
	public ResultVo updatePwdByCode(String username,String code,String newPwd,String reNewPwd) {
		userdao.updatePwdByCode(username, newPwd);
		return ResultVo.getSuccessVo("success");
		
	}
}
